﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sern.Abstracts.Common;
using Sern.Abstracts.Feeder;
using Sern.Abstracts.Splitter;
using Sern.Abstracts.Tracker.DataContracts;
using Sern.Common;
using Sern.ServiceImplementation;
using Sern.ServiceImplementation.MapReduce;
using Microsoft.Practices.Unity;

namespace LineFeeder
{
    public class Feeder : IFeeder
    {
        public void Start()
        {
            var trackerClient = 
                MapReduceClientTrackerProxyFactory.CreateProxy2(
                    ComponentLocator.Unity.Resolve<IBindingFactory>()
                    [ClientType.Tracker](),
                    "localhost:8080/Tracker");


            //TODO: Read the text file line by line here.
            using (TextReader reader = File.OpenText("SampleDocument.txt"))
            {
                var lineNumber = 0;
                string line = "";
                while ((line = reader.ReadLine()) != null)
                {
                    var filterProxy = MapReduceProxyFactory
                        <ISplitter<SelfHealingKey<int>, string>, SelfHealingKey<int>, string>
                        .CreateMapReduceProxy(
                            () => MapReduceClientTrackerProxyFactory.CreateProxy2(
                                ComponentLocator.Unity.Resolve<IBindingFactory>()
                                    [ClientType.Tracker](),
                                "localhost:8080/Tracker")
                        );

                    var lineKey = SelfHealingKey.CreateNew(lineNumber, 0);
                    
                    filterProxy.Proxy.Handle(
                        lineKey,
                        line
                    );
                }
            }
        }
    }
}
